package com.liangwj.springbootweb.controller;

import com.liangwj.springbootweb.domain.User;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;

/**
 * @author Liangwenjun
 * @date 2018-12-11
 * @version 1.0.0
 */
@RestController
@RequestMapping("/users")
public class UserController {

    private final static Logger LOGGER = LoggerFactory.getLogger(UserController.class);
    //创建线程安全的Map
    private static Map<Long, User> userMaps = Collections.synchronizedMap(new HashMap<>());

    @ApiOperation(value = "获取用户列表", notes = "")
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public List<User> getUserList() {
        List<User> userList = new ArrayList<>(userMaps.values());
        LOGGER.info("getUserList():userList={}", userList.toArray());
        return userList;
    }

    @ApiOperation(value = "创建用户", notes = "根据User对象创建用户", httpMethod = "POST")
    /*@ApiImplicitParams(value = {
            @ApiImplicitParam(name = "user", value = "用户详细实体User", required = true, dataType = "User", paramType = "query"),
    })*/
    @ApiParam()
    @RequestMapping(value = "/", method = RequestMethod.POST)
    //@ModelAttribute -- 此注解会自动展开javabean的所有属性,如果需要对单个属性说明.需要在javabean中对单个属性@ApiModelProperty
//    public String postUser(@ModelAttribute User user) {
    public String postUser(@RequestBody User user) {//JSON的格式传参
        LOGGER.info("postUser():user={}", user.toString());
        userMaps.put(user.getId(), user);
        return "SUCCESS";
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public User getUserById(@PathVariable Long id) {
        return userMaps.get(id);
    }

    /** 更新user*/
    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    public String putUser(@ModelAttribute User user, @PathVariable Long id) {
        LOGGER.info("putUser():id={}", id);
        LOGGER.info("putUser():user={}", user);
        User u = userMaps.get(id);
        u.setUserName(user.getUserName());
        u.setPassword(user.getPassword());

        userMaps.put(id, u);
        return "SUCCESS";
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public String delUser(@PathVariable Long id) {
        userMaps.remove(id);
        return "SUCCESS";
    }

    /**
     * 测试图片下载
     * @param imgUrl
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/download")
    public String downloadJpg(String imgUrl, HttpServletRequest request, HttpServletResponse response) {
        String fileName = imgUrl.substring(imgUrl.lastIndexOf('/') + 1);
        BufferedInputStream is = null;
        BufferedOutputStream os = null;
        try {
            URL url = new URL(imgUrl);
            response.setContentType("application/x-msdownload;");
            response.setHeader("Content-disposition", "attachment; filename=" + new String(fileName.getBytes("utf-8"), "ISO8859-1"));
            response.setHeader("Content-Length", String.valueOf(url.openConnection().getContentLength()));
            is = new BufferedInputStream(url.openStream());
            os = new BufferedOutputStream(response.getOutputStream());
            byte[] buff = new byte[2048];
            int bytesRead;
            while (-1 != (bytesRead = is.read(buff, 0, buff.length))) {
                os.write(buff, 0, bytesRead);
            }
            if (is != null)
                is.close();
            if (os != null)
                os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }
}
